<?php

namespace app\api\model;

use app\admin\controller\crud\Log;
use app\exceptions\ApiException;
use ba\Exception;
use EasyWeChat\Factory;
use think\facade\Db;

class Pay
{

    public function payMassif($params)
    {
        $massif_id = $params['massif_id'] ?? '';
        try {
            //验证数据
            $validate = new \app\api\validate\Pay();
            $validate->check($params);
        } catch (\Throwable $e) {
            throw new ApiException($e->getMessage());
        }

        try {
            Db::startTrans();
            //获取用户信息
            $member = (new Member())->where(['id' => $params['member_id']])->find();
            if (!$member) {
                throw new ApiException('用户不存在');
            }
            //查询地块信息
            $massifItem = (new Massif())->where(['id' => $massif_id, 'status' => 1])->lock(true)->find();
            if (!$massifItem) {
                throw new ApiException('数据不存在');
            }
            if ($massifItem['is_lock'] == 1) {
                throw new ApiException('已被锁定，请刷新后重试');
            }
            //查询品类
            $land = (new Land())->where(['id' => $massifItem['land_id'], 'status' => 1])->find();
            if (!$land) {
                throw new ApiException('土地品类不存在,请刷新后重试');
            }

            $title = $land['name'] . "-" . $massifItem['name'];
            $out_trade_no = $this->build_order_no('MF');
            $pay_amount = $massifItem['price'];
            $orderArr['out_trade_no'] = $out_trade_no;
            $orderArr['member_id'] = $params['member_id'];
            $orderArr['land_id'] = $massifItem['land_id'];
            $orderArr['massif_id'] = $massif_id;
            $orderArr['land_name'] = $land['name'];
            $orderArr['massif_name'] = $massifItem['name'];
            $orderArr['pay_amount'] = $pay_amount;
            $orderArr['image'] = $land['image'];
            $orderArr['username'] = $params['username'];
            $orderArr['phone'] = $params['phone'];
            $orderArr['address'] = $params['address'];
            $orderArr['address_detail'] = $params['address_detail'];
            $orderArr['create_time'] = time();
            $orderArr['update_time'] = time();

            (new Order())->save($orderArr);
            $config = $this->toPay($title, $out_trade_no, $pay_amount, 'orderCallback', $member['openid']);
            Db::commit();
            if ($config) {
                return api_message($config);
            } else {
                throw new ApiException('下单失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }


    public function toPay($body, $out_trade_no, $pay_amount, $callback, $openid)
    {
//        $pay_amount = 0.01;
        $app = Factory::payment(config('wechat.wechat_pay'));
        $jssdk = $app->jssdk;
        $data = [
            'body' => $body,
            'out_trade_no' => $out_trade_no,
            'total_fee' => $pay_amount * 100,
            'notify_url' => env('domain.image_url') . '/index.php/call/pay/' . $callback, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid, //
        ];
        \think\facade\Log::info(json_encode($data));
        $result = $app->order->unify($data);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $config = $jssdk->sdkConfig($result['prepay_id']); // 返回数组
            if (isset($config['timestamp'])) { // 检查timestamp是否存在
                $config['timeStamp'] = $config['timestamp']; // 复制timestamp的值到timeStamp
                unset($config['timestamp']); // 删除timestamp键
            }
            return $config;
        } else {
           throw new ApiException($result['err_code_des']);
        }
    }


    //生成订单
    public function build_order_no($prefix)
    {
        return $prefix . date('ymd') . substr(
                implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))),
                0,
                8
            );
    }


}